package org.opensource.yabts.server;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.opensource.yabts.client.GreetingService;
import org.opensource.yabts.server.bean.Project;
import org.opensource.yabts.service.SpringService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Service;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
@Service("greetingService")
public class GreetingServiceImpl extends RemoteServiceServlet implements GreetingService {

	@Autowired
	private SpringService springService;

	// We'll be calling SQL statements. SimpleJdbcTemplate is a perfect tool.
	private SimpleJdbcTemplate jdbcTemplate;
	
    public SimpleJdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
 
    @Autowired
    @Required
    public void setJdbcTemplate(SimpleJdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid.
		// if (!FieldVerifier.isValidName(input)) {
		// // If the input is not valid, throw an IllegalArgumentException back
		// to
		// // the client.
		// throw new IllegalArgumentException(
		// "Name must be at least 4 characters long");
		// }

		// Escape data from the client to avoid cross-site script
		// vulnerabilities.
		input = escapeHtml(input);

		// Delegate to SpringService and return the result
		return springService.echo("hello");
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html
	 *            the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}


	public Project getProject(Long id) throws IllegalArgumentException {

		try {
			// Prepare SQL statement
			String sql = "SELECT id, name FROM project WHERE id = ?";
			
			// Assign values to parameters
			Object[] parameters = new Object[] {id};
			
			// Map SQL result to a Java object
			RowMapper<Project> mapper = new RowMapper<Project>() {  
		        public Project mapRow(ResultSet rs, int rowNum) throws SQLException {
		        	Project project = new Project();
		        	project.setName(rs.getString("name"));
		            return project;
		        }
		    };
		    
		    // Run query then return result
		    return jdbcTemplate.queryForObject(sql, mapper, parameters);
		
		} catch (Exception e) {
			return null;
		}	
	}
}
